package com.kingdee.openimport.patch_service.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 用于发送更新补丁消息的MQ，目前使用RabbitMQ
 * 因为这个类似于广播，因此注意客户端的queue命名注意唯一性。可以使用UUID
 * Created by Niki on 2018/5/10 14:22
 */
@Configuration
@Slf4j
public class MQConfig {
    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.port}")
    private int port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(this.host);
        connectionFactory.setPort(this.port);
        connectionFactory.setUsername(this.username);
        connectionFactory.setPassword(this.password);
        log.info("RabbitMQ connection {}:{} success!", this.host, this.port);
        return connectionFactory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }

    /* 补丁通知服务Exchange名 */
    private static final String EXCHANGE_PATH_NAME = "EAS:PATCH:SERVICE:EXCHANGE";
    /* 补丁通知服务Queue名 */
    private static final String QUEUE_PATH_NAME = "EAS:PATCH:SERVICE:QUEUE";

    public static String getExchangeKey() {
        return EXCHANGE_PATH_NAME;
    }

    public static String getRoutingKey() {
        return QUEUE_PATH_NAME;
    }

    /**
     * fanout是发送消息最快的一种类型
     * @return
     */
    @Bean
    public FanoutExchange patchServiceExchange() {
        FanoutExchange exchange = new FanoutExchange(EXCHANGE_PATH_NAME, true, false);
        log.info("path service exchange:[{}] create success !", EXCHANGE_PATH_NAME);
        return exchange;
    }

}
